<!doctype html>
<html lang="{{ config('app.locale') }}">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, viewport-fit=cover">
  <meta name="_token" content="{{ csrf_token() }}"/>

  <title>Qkids久趣英语</title>
  <script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/rem.js"></script>
  <link href="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/css/invite.css?v={{config('app.version')}}" rel="stylesheet"
        type="text/css">
</head>
<body>
<img class="banner" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/banner.jpg" alt="banner"/>
<div class="main">
  <img class="main-title" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/main-title.jpg" alt="标题"/>
  <div class="content">
    <span class="num" id="num-first">1</span>
    <img src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/step-done.png" class="step-done" alt="success"/>
    <span class="content-title">赠送免费课时给好友</span>
    <span class="content-time" id="count-time">3天内有效</span>
  </div>
  <div class="wrap">
    <div class="given">
      <div class="given-left">
        <div class="given-left-title">四人班</div>
        <div class="given-left-desc">免费1课时</div>
        <span class="given-semicircle"></span>
        <span class="given-semicircle"></span>
      </div>
      <div class="given-right">
        <div class="given-right-title" id="given-right-title">赠送好友</div>
      </div>
    </div>
  </div>
  <div class="content content-disabled">
    <span class="num">2</span>
    <img src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/step-done.png" class="step-done" alt="success"/>
    <span class="content-title">好友购课</span>
    <span class="content-time" id="buy-count-time">30天内购课有效</span>
  </div>
  <div class="wrap wrap-disabled">
    <div class="given purchase">
      <img class="user-avator" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/logo.png" alt="头像"/>
      <span class="user-name">你的朋友</span>
      <span class="user-status">尚未购课</span>
    </div>
  </div>
  <div class="content content-disabled">
    <span class="num">3</span>
    <img src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/step-done.png" class="step-done" alt="success"/>
    <span class="content-title">免费获得2课时</span>
  </div>

  <div class="wrap wrap-disabled">
    <div class="given given-done">
      <div class="given-left success-given-left">
        <div class="given-left-title">四人班</div>
        <div class="given-left-desc"></div>
        <span class="given-semicircle"></span>
        <span class="given-semicircle"></span>
      </div>
      <div class="given-right success-given-right">
        <div class="success-given-right-num">2</div>
        <div class="success-given-right-desc">课时</div>
      </div>
    </div>
  </div>
</div>
<div class="main">
  <div class="rule-title">
    <strong class="rule-title-dot">·</strong>
    <span class="rule-title-content">活动规则</span>
    <strong class="rule-title-dot">·</strong>
  </div>
  <div class="rule-item">
    <span class="rule-item-num">1</span>
    <span class="rule-item-content">本次活动为邀请制，仅收到邀请的学员拥有赠课特权（每上完5节课，有机会获得1次赠课特权）；</span>
  </div>
  <div class="rule-item">
    <span class="rule-item-num">2</span>
    <span class="rule-item-content">新用户领取赠课并成功购买久趣课程后，发起邀请者即可免费获得2课时，有效期一年。</span>
  </div>
</div>

<img class="logo" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/qkids.jpg" alt="logo"/>

<div class="account">
  当前账号：
  <span class="account-phone">未登录</span>
  <span id="switch-account-invite" class="switch-account">登录</span>
</div>

<div class="copy-right-warp">
  <div class="copy-right">
    <div class="copy-right-time">Copyright @2017-2018 Qkids All Rights Reserved</div>
    <div class="copy-right-num">闽ICP备12021838号-3</div>
  </div>
</div>

<div class="gift">
  <span id="gift"></span>
  <img class="gift-arrow" src="{{env('CDN_RESOURCE')}}/mobile/campaign/invite/img/gift-arrow.png" alt="arrow"/>
</div>
<div class="alert-wrap">
  <div class="alert">
    <div class="alert-title">TIPS</div>
    <div class="alert-desc">公众号点击『预约上课』→『我的』→『我的课时』，即可查看您获得的课时</div>
    <div class="alert-btn">明白了</div>
  </div>
</div>

<div class="share-mask" id="share">
  <div class="share-arrow"></div>
  <div class="share-text">点击分享给好友 ^ _ ^</div>
</div>

<div id="alertBox" class="alert-box"></div>

<script type="text/javascript" src="https://static-app.97kid.com/wx/js/zepto.min.js"></script>
<!--引入微信js-SDK-->
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src=" {{env('CDN_RESOURCE')}}/js/mobile/wx_config.js?v={{config('app.version')}}"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/Zepto_fx_methods.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/login.js?v={{config('app.version')}}"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/AV.analytics.js"></script>

<script type="text/javascript">


  (function ($) {
    $(function () {
      if (!utils.getQueryString('_c')) {
        var QKidsChannel = JSON.parse(window.localStorage.getItem('QKidsChannel'))
        if (!(QKidsChannel && QKidsChannel.expires > new Date().getTime() / 1000)) {
          window.localStorage.setItem('QKidsChannel', JSON.stringify({
            rawData: 'invite_share',
            expires: new Date().getTime() / 1000 + 24 * 3600
          }))
        }
      }

      if (!utils.getQueryString('_r')) {
        var QKidsReference = JSON.parse(window.localStorage.getItem('QKidsReference'))
        if (!(QKidsReference && QKidsReference.expires > new Date().getTime() / 1000)) {
          window.localStorage.setItem('QKidsReference', JSON.stringify({
            rawData: 'invite_share',
            expires: new Date().getTime() / 1000 + 24 * 3600
          }))
        }
      }

      window.analytics = AV.analytics({
        appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
        appKey: 'jqyWxLyobpsmdwsJddJlDheb',
        channel: /(MicroMessenger)/i.test(navigator.userAgent) ? 'weixin' : ''
      })
      analytics.send({
        event: 'p006_invite_pv'
      })

      var status = null
      var glcode = ''
      var friend = '你的朋友'
      var shareFlag = ''
      var configOption = {
        timestamp: '{{$signature['timestamp']}}',
        nonceStr: '{{$signature['nonceStr']}}',
        signature: '{{$signature['signature']}}',
        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone']
      }
      var wxconfig = new WxConfig(configOption, 'invite')
      wxconfig.activeShare(shareFlag, '', shareMsg())

      var account = new Account()

      account.forceLogin = true
      account.getUserInfo(function (err, userInfo) {
        account.forceLogin = true
        if (!err && userInfo && userInfo.shareFlag) {
          shareFlag = userInfo.shareFlag
          wxconfig.activeShare(shareFlag, '', shareMsg())
          if(userInfo && userInfo.mobile){
            $('.account-phone').text(userInfo.mobile.replace(/^(\d{3})\d{4}(\d+)/, '$1****$2'))
            $('#switch-account-invite').text('切换账号')
          }

          account.ajax({
            type: 'GET',
            path: '/s/events/giftLesson',
            success: function (data) {
              var givenEle = $('.given')
              var numEle = $('.num')
              var stepDoneEle = $('.step-done')
              var contentEle = $('.content')
              var wrapEle = $('.wrap')
              var giftEle = $('#gift')
              var giftArrowEle = $('.gift-arrow')

              status = data.status
              glcode = data.code
              wxconfig.activeShare(shareFlag, '', shareMsg())
              
              /**
               * status: 领取状态
               * 0：未领取
               * 1：未领取过期
               * 2：已领取
               * 3：领取未购课过期
               * 4：领取且购课
               **/
              if (status === 0) {
                giftEle.text('免费赠送好友')
                giftArrowEle.css({'display': 'block'})
                givenEle.first().fadeIn()
                if(data.expiredAt){
                  showCountDown(data.expiredAt, $("#count-time"))
                }
              } else if (status === 2) {
                if(data.acceptance && data.acceptance.studentId){
                  getWechatUserInfo(data.acceptance.studentId, true)
                }

                if(data.acceptance && data.acceptance.expiredAt){
                  showCountDown(data.acceptance.expiredAt, $("#buy-count-time"))
                }
                
                numEle.first().css({'display': 'none'})
                stepDoneEle.first().css({'display': 'block'})
                contentEle.eq(1).removeClass('content-disabled')
                wrapEle.eq(1).removeClass('wrap-disabled')
                givenEle.eq(1).css({'display': 'flex'})
                giftEle.text('等待好友购课')
                giftArrowEle.css({'display': 'block'})
                $('#count-time').text('')
              } else if (status === 4) {
                var ms;
                var date;
                // 有效期为365天
                if(data.acceptance && data.acceptance.giftedAt){
                  ms = (data.acceptance.giftedAt + 365*24*60*60)*1000
                }else {
                  ms = (new Date()).getTime() + 365*24*60*60*1000
                }
                var date = new Date(ms)
                var year = date.getFullYear()
                var month = date.getMonth() + 1
                var day = date.getDate()
                var str = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + "到期"
                $(".given-left-desc").text(str)

                numEle.first().css({'display': 'none'})
                stepDoneEle.first().css({'display': 'block'})
                numEle.eq(1).css({'display': 'none'})
                stepDoneEle.eq(1).css({'display': 'block'})
                contentEle.eq(1).removeClass('content-disabled')
                wrapEle.eq(1).removeClass('wrap-disabled')
                contentEle.last().removeClass('content-disabled')
                wrapEle.last().removeClass('wrap-disabled').css({'display': 'block'})
                givenEle.last().css({'display': 'block'})
                giftEle.text('查看免费课时')
                giftArrowEle.css({'display': 'block'})
                $('#count-time').text('')

              } else if (status === 1 || status === 3) {
                $('.alert-title').text('很遗憾')
                $('.alert-desc').text('您未能获得本次的免费课时，请留意下次特权通知。')
                $('.alert-wrap').css({'display': 'flex'})
                $('.gift').addClass('gift-disabled')
                $('#count-time').text('')
                
                if (status === 3) {
                  if (data.acceptance && data.acceptance.studentId) {
                    getWechatUserInfo(data.acceptance.studentId, true)
                  }
                  $('.content-time').last().text('已超时')
                  numEle.first().css({'display': 'none'})
                  stepDoneEle.first().css({'display': 'block'})
                  contentEle.eq(1).removeClass('content-disabled')
                  wrapEle.eq(1).removeClass('wrap-disabled')
                  givenEle.eq(1).css({'display': 'flex'})
                  giftEle.text('朋友未购课 😂')
                } else {
                  giftEle.text('朋友没有准时领取你的心意 😂')
                  givenEle.first().fadeIn().addClass('given-fail')
                }
              } else {
                giftEle.text('本次特权已失效')
                $('.gift').addClass('gift-disabled')
              }
              getWechatUserInfo(userInfo.id)
            },
            error: function (err) {
              $('#gift').text(err.message)
              $('.gift').addClass('gift-disabled')
              $('.given').first().fadeIn().addClass('given-fail')
              wxconfig.activeShare(shareFlag, '', shareMsg())
              
              $.toastAlert(err.message, 2)
            }
          })
        }
      })

      $('#given-right-title').on('click', function (e) {
        $('#share').fadeIn()
      })

      $('#share').on('click', function (e) {
        $('#share').fadeOut()
      })

      $('.gift').on('click', function (e) {
        if (status === 0) {
          $('#share').fadeIn()
        } else if (status === 4) {
          $('.alert-wrap').css({'display': 'flex'})
        }
      })

      $('.alert-btn').on('click', function (e) {
        $('.alert-wrap').css({'display': 'none'})
      })

       //切换账号
       $('#switch-account-invite').off('click').on('click',function() {
          $('.account-mask').fadeOut();
          account.forceLogin = true;
          account.checkLoginStatus(function() {
            account._showLogin(function () {}, true);
          });
        });
      

      // 设置分享信息
      function shareMsg () {
        return {
          title: '来自' + friend + ': 送你1节孩子最爱的北美外教课，免费哟~',
          desc: '快来跟我们做同学吧~ ',
          link: window.location.protocol + '//' + window.location.host + '/wx/invite/share?_c=invite_share&_r=' + shareFlag + '&glcode=' + glcode,
          imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png',
          success: function (target) {
            analytics.send({
              event: 'p006_invite_share_success',
              attr: {
                gid: glcode,
                target: target
              }
            })
          }
        }
      }

      // 倒计时判断
      function showCountDown(times, obj) {
        var remainTimes = times -  ((new Date()).getTime())/1000
        var days = remainTimes/(60*60*24);

        if(days > 1){
          obj.text('倒计时' + Math.ceil(days) + '天')
        }else if(days > 0){
          countDown(remainTimes, obj)
        }else {
          obj.text('已超时')
        }
      }

      // 倒计时
      function countDown (times, obj) {
        var timer = null
        timer = setInterval(function () {
          setSecond(times, obj)
          if (times <= 0) {
            clearInterval(timer)
            obj.text('已超时')
          }
          times--
        }, 1000)
      }

      // 倒计时读秒
      function setSecond (times, obj) {
        var day = 0,
          hour = 0,
          minute = 0,
          second = 0
        if (times > 0) {
          day = Math.floor(times / (60 * 60 * 24))
          hour = Math.floor(times / (60 * 60)) - (day * 24)
          minute = Math.floor(times / 60) - (day * 24 * 60) - (hour * 60)
          second = Math.floor(times) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
        }
        if (hour <= 9) hour = '0' + hour
        if (minute <= 9) minute = '0' + minute
        if (second <= 9) second = '0' + second
        obj.text('倒计时' + day + ':' + hour + ':' + minute + ':' + second)
      }

      // 根据id获取昵称
      function getWechatUserInfo (id, isInvitedUser) {
        account.ajax({
          type: 'GET',
          path: '/s/students/socials?ids=' + id,
          success: function (data) {
            if (data && data.length > 0) {
              if (isInvitedUser) {
                if(data[0].avatar){
                  $(".user-avator").attr("src", data[0].avatar)
                }
                if(data[0].nickname){
                  $(".user-name").text(data[0].nickname)  
                }else {
                  $(".user-name").text('你的朋友')
                }
              }else {
                if(data[0].nickname) {
                  friend = data[0].nickname
                }
                wxconfig.activeShare(shareFlag, '', shareMsg())
              }
            }
          },
          error: function (err) {
            $.toastAlert(err.message, 2)
            if (isInvitedUser) {
              $(".user-name").text("你的朋友")
            }else {
              wxconfig.activeShare(shareFlag, '', shareMsg())
            }
          }
        })
      }
    })
  })(window.Zepto)
</script>
</body>
</html>